package String;

public class _859_BuddyStrings {
    public boolean buddyStrings(String A, String B) {
        //different character's quantity
        int count = 0;
        //the substring which need to be reverse's interval
        int start = 0,end = 0;
        //note : if the string has duplicate characters,it can do buddy while not change any character.
        int[] characterConut = new int[26];
        boolean buddy = false;
        if (A.length() == B.length()) {
            for (int i = 0; i < A.length(); i++) {
                characterConut[A.charAt(i) - 'a']++;
                if (A.charAt(i) != B.charAt(i)) {
                    count++;
                    if (count == 1) {
                        start = i;
                    } else if (count == 2) {
                        end = i;
                        String rev = new StringBuffer(A.substring(start, end + 1)).reverse().toString();
                        if (rev.equals(B.substring(start, end + 1))) {
                            buddy = true;
                        }
                    } else {
                        break;
                    }
                }
            }
        }
        boolean duplicate = false;
        for (int i : characterConut) {
            if (i > 1) {
                duplicate = true;
            }
        }
        return (buddy && count == 2) ||(duplicate==true && count==0);
    }
}
